<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索 -->
        <el-form :model="form" ref="form">
          <div class="filter-container">
            <!-- Row 组件 提供 gutter 属性来指定每一栏之间的间隔，默认间隔为 0。 -->
            <el-row :gutter="20">
              <el-col :span="7">
                <el-form-item
                  :label="$t('table.keywords') + '：'"
                  prop="keyword"
                >
                  <el-input
                    style="width: 180px"
                    class="filter-item"
                    v-model="form.keyword"
                    @keyup.enter="query"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="$t('table.state') + '：'" prop="state">
                  <el-select
                    class="filter-item"
                    style="width: 180px"
                    v-model="form.state"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="item in status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item>
                  <el-button size="small" @click="resetForm">{{
                    $t("table.clear")
                  }}</el-button>
                  <el-button
                    :loading="isLoading"
                    size="small"
                    type="primary"
                    @click="query"
                    >{{ $t("table.search") }}</el-button
                  >
                  <el-button
                    style="margin: 0 0 20px 20px"
                    type="primary"
                    icon="el-icon-document"
                    @click="handleDownload"
                  >
                    Export Excel
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>

            <el-button
              class="filter-item fr"
              size="small"
              style="margin-left: 10px"
              type="primary"
              icon="el-icon-edit"
              @click="addArticle"
              >{{ $t("table.add") }}</el-button
            >
            <!-- 数据记录 -->
            <el-alert
              v-if="cResultTip"
              :title="cResultTip"
              type="info"
              class="alert"
              :closable="false"
              show-icon
            ></el-alert>
          </div>
        </el-form>
        <!-- 数据列表 -->
        <el-table
          :data="articles"
          v-loading="isLoading"
          element-loading-text="给我一点时间"
          fit
          highlight-current-row
          style="width: 100%"
          border
        >
          <el-table-column type="index" :index="indexMethod"> </el-table-column>
          <el-table-column align="center" :label="$t('table.articleTitle')">
            <template slot-scope="scope">
              <span style="margin-right: 7px">{{ scope.row.title }}</span>
              <!-- <a
                :href="scope.row.videoURL"
                v-if="scope.row.videoURL ? true : false"
              >
                <svg-icon icon-class="video"></svg-icon>
              </a> -->
              <span
                v-if="scope.row.videoURL ? true : false"
                id="video"
                @click="checkVideoFun(scope.row)"
              >
                <svg-icon icon-class="video"></svg-icon>
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('table.views')">
            <template slot-scope="scope">
              <span>{{ scope.row.visits }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('table.operator')">
            <template slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('table.operationDate')">
            <template slot-scope="scope">
              <span>{{
                dayjs(scope.row.createTime).format("YYYY-MM-DD hh:mm:ss")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('table.state')" width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.state == 1">{{ $t("table.enable") }}</span>
              <span v-else>{{ $t("table.prohibit") }}</span>
            </template>
          </el-table-column>
          <!-- 操作按钮 -->
          <el-table-column
            align="center"
            :label="$t('table.operationType')"
            width="280"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="preview(scope.row)">{{
                $t("table.preview")
              }}</el-button>
              <el-button
                type="text"
                size="small"
                @click="switchStatus(scope.row)"
              >
                <span>{{
                  scope.row.state ? $t("table.prohibit") : $t("table.enable")
                }}</span>
              </el-button>
              <el-button
                type="text"
                size="small"
                :disabled="scope.row.state ? false : true"
                @click="edit(scope.row)"
                >{{ $t("table.edit") }}</el-button
              >
              <el-button
                v-if="scope.row.status != 'deleted'"
                size="small"
                type="text"
                :disabled="scope.row.state ? false : true"
                @click="deleteArticle(scope.row)"
                >{{ $t("table.delete") }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination" v-show="total">
          <div class="pages">
            <el-pagination
              background
              @size-change="hSizeChange"
              @current-change="hCurrentChange"
              :current-page="Number(form.page)"
              :total="Number(total)"
              :page-size="Number(form.pagesize)"
              :page-sizes="[10, 20, 30, 50]"
              layout="prev, pager, next, sizes, jumper"
            ></el-pagination>
          </div>
        </div>
      </el-card>
      <!-- 新增\修改 -->
      <el-dialog
        :title="Title"
        :visible.sync="isShowDialog"
        :close-on-click-modal="false"
        ref="addDialog"
      >
        <div class="add-form">
          <el-form
            :rules="rule"
            ref="dataForm"
            :model="formData"
            label-position="left"
            label-width="80px"
          >
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="formData.title"></el-input>
            </el-form-item>
            <el-form-item label="文章内容" prop="articleBody">
              <quill-editor
                ref="myQuillEditor"
                @blur="onEditorBlur($event)"
                v-model="formData.articleBody"
              >
              </quill-editor>
            </el-form-item>
            <el-form-item label="视频地址" prop="videoURL">
              <el-input v-model="formData.videoURL"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
        </div>
      </el-dialog>
      <!-- 预览 -->
      <el-dialog title="预览文章" :visible.sync="dialogVisible" width="70%">
        <h1>{{ articleContext.title }}</h1>
        <p>
          {{ articleContext.createTime }}&nbsp;&nbsp; {{ username }}&nbsp;&nbsp;
          <svg-icon icon-class="view"></svg-icon>&nbsp;{{
            articleContext.visits
          }}
        </p>
        <p id="body"></p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 视频弹窗 -->
      <div class="mask" v-if="videoState === true"></div>
      <!-- 弹窗 -->
      <div class="cha" v-if="videoState === true" @click="masksCloseFun">×</div>
      <div class="videomasks" v-if="videoState === true">
        <!-- 视频：h5的视频播放video -->
        <video
          :src="videoSrc"
          controls="controls"
          autoplay
          width="100%"
          height="100%"
        >
          您的浏览器不支持 video 标签。
        </video>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { status } from '@/api/hmmm/constants'
import {
  list,
  remove,
  add,
  update,
  detail,
  changeState
} from '@/api/hmmm/articles.js'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  name: 'ArticlesList',
  components: {
    quillEditor
  },
  data () {
    return {
      formData: {
        title: '', // 文章标题
        articleBody: '', // 文章内容
        videoURL: '' // 视频地址
      },
      // 表单验证
      rule: {
        title: [
          { required: true, message: '文章标题不能为空', trigger: 'blur' }
        ],
        articleBody: [
          { required: true, message: '文章内容不能为空', trigger: 'blur' }
        ]
      },
      articles: [],
      form: {
        state: null,
        keyword: '',
        page: 1,
        pagesize: 10
      },
      total: 0,
      isLoading: false,
      isShowDialog: false,
      dialogVisible: false,
      data: [],
      articleContext: {},
      username: '',
      videoState: false,
      videoSrc: ''
    }
  },
  created () {
    this.getArticleList()
  },
  methods: {
    // 富文本编辑器单独校验
    onEditorBlur (e) {
      this.$refs.dataForm.validateField('articleBody')
    },
    submit () {
      this.$refs.dataForm.validate(async (flag) => {
        if (!flag) return
        try {
          if (this.data.id) {
            // 修改文章
            const res = await update(this.data)
            console.log(res)
          } else {
            const res = await add(this.formData)
            console.log(res)
          }
          this.close()
          this.getArticleList()
        } catch (err) {
          console.log(err)
        }
      })
    },
    buildParams () {
      const paramsObj = {}
      const { page, pagesize, keyword, state } = this.form
      // 如果某一个参数是null,则axios就不会发这个参数
      // 如果某一个参数是""，axios是会发出这个参数
      paramsObj.page = page || null
      paramsObj.pagesize = pagesize || null
      paramsObj.keyword = keyword || null
      paramsObj.state = state === '' ? null : state
      return paramsObj
    },
    /**
     * 获取文章列表数据
     */
    async getArticleList () {
      this.isLoading = true
      // 构建查询参数
      const paramsObj = this.buildParams()
      try {
        const { data } = await list(paramsObj)
        // console.log(data)
        this.articles = data.items
        this.total = data.counts
        this.isLoading = false
      } catch (error) {
        // console.log(error)
        this.isLoading = true
      }
    },
    // 列表序号
    indexMethod (index) {
      return (this.form.page - 1) * this.form.pagesize + index + 1
    },
    // 更改每页显示的条数
    hSizeChange (val) {
      this.form.pagesize = val

      if (this.form.page === 1) {
        this.getArticleList()
      }
    },
    // 点击某一个页码
    hCurrentChange (curPage) {
      this.form.page = curPage
      this.getArticleList()
    },
    // 重置整个表单
    resetForm () {
      // el 表单组件上有一个resetFields方法
      this.$refs.form.resetFields()
      this.getArticleList()
    },
    // 搜索信息
    query () {
      // 重置页码
      this.form.page = 1
      // 重发请求
      this.getArticleList()
    },
    /**
     * 删除当前数据
     */
    deleteArticle (data) {
      this.$confirm('此操作将永久删除该文章，是否继续？', '温馨提示')
        .then(async () => {
          const res = await remove(data)
          console.log(res)
          this.$message.success('删除成功')
          this.getArticleList()
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },
    /**
     * 新增文章
     */
    addArticle () {
      this.isShowDialog = true
    },
    /**
     * 修改文章
     * @param {*} id 文章id
     */
    edit (data) {
      this.isShowDialog = true
      this.data = data
      this.formData = data
    },
    /**
     * 预览文章
     */
    async preview (details) {
      this.username = details.username
      this.dialogVisible = true
      const { data } = await detail(details)
      this.articleContext = data
      const body = document.querySelector('#body')
      body.innerHTML = this.articleContext.articleBody
    },
    /**
     * 改变文章状态
     * @param {*} details
     */
    async switchStatus (details) {
      details.state = !details.state
      if (details.state) {
        details.state = 1
      } else {
        details.state = 0
      }
      const res = await changeState(details)
      console.log(res)
      this.$message.success('操作成功')
      console.log(details.state)
      console.log(details.id)
    },
    // 点击按钮出现弹窗播放视频
    checkVideoFun (data) {
      console.log(data)
      this.videoSrc = data.videoURL
      this.videoState = true
    },
    masksCloseFun () {
      this.videoState = false
    },
    /**
     * 关闭弹框
     */
    close () {
      this.$refs.dataForm.resetFields()
      this.formData = {
        title: '', // 文章标题
        articleBody: '', // 文章内容
        videoURL: '' // 视频地址
      }
      this.isShowDialog = false
    },
    /**
     * 导出 excel 文件
     */
    handleDownload () {
      import('@/vendor/Export2Excel').then((excel) => {
        console.log(this.articles)
        const headersArr = ['文章标题', '阅读数', '操作人', '操作时间', '状态']
        const headersRelations = {
          文章标题: 'title',
          阅读数: 'visits',
          操作人: 'creatorID',
          操作时间: 'createTime',
          状态: 'state'
        }
        const data = this.formateDate(this.articles, headersArr, headersRelations)
        console.log(data)
        excel.export_json_to_excel({
          // 表头
          header: headersArr,
          // 数据
          data,
          // 文件
          filename: '面试技巧文章',
          // 宽度自适应
          autoWidth: true,
          // 后缀名
          bookType: 'xlsx'
        })
      })
    },

    formateDate (articles, headersArr, headersRelations) {
      const result = []
      articles.forEach(item => {
        const tempArr = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          const value = item[englishKey]
          tempArr.push(value)
        })
        result.push(tempArr)
      })
      return result
    }
  },
  computed: {
    dayjs () {
      return dayjs
    },
    cResultTip () {
      return `共 ${this.total} 条记录`
    },
    status () {
      return status
    },
    Title () {
      return this.id ? '修改文章' : '新增文章'
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.alert {
  margin: 10px 0px;
}
.pagination {
  margin-top: 10px;
}
</style>

<style scoped>
.mask {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 10;
  background-color: #000000;
  opacity: 0.6;
}
/* 内容层 z-index要比遮罩大，否则会被遮盖 */
.cha {
  position: absolute;
  left: 50%;
  top: 20%;
  width: 50px;
  height: 50px;
  transform: translate(-50%, -50%);
  text-align: center;
  line-height: 50px;
  cursor: pointer;
  font-size: 30px;
  color: #fff;
  border-radius: 50%;
  background-color: #000000;
  opacity: 0.7;
  z-index: 20;
}
.videomasks {
  max-width: 800px;
  max-height: 600px;
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 20;
  transform: translate(-50%, -50%);
}
</style>

<style>
.el-table th {
  background-color: #fafafa;
}
.el-table th.is-leaf {
  border-bottom: 2px solid #e8e8e8;
}
.disabled td {
  background-color: #f9f9f9;
  color: #c1c1c1;
}
.disabled .el-button--primary,
.disabled .el-button--danger {
  background-color: #dbdada;
  border: 1px solid #dbdada;
  color: #999;
  cursor: not-allowed;
}
</style>

<style>
.dialog-footer {
  display: flex;
  justify-content: right;
}
</style>
